package cn.tellsea.auth.security.controller;

import cn.hutool.json.JSONUtil;
import cn.tellsea.auth.security.entity.User;
import cn.tellsea.auth.security.utils.JwtTokenUtils;
import cn.tellsea.auth.security.utils.SecurityUtils;
import cn.tellsea.base.common.dto.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * 登录控制层
 *
 * @author Tellsea
 * @date 2023/8/8
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class LoginController {

    private final UserDetailsService userDetailsService;
    private final JwtTokenUtils jwtTokenUtils;

    /**
     * 注册
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result<User> register(@RequestParam String username, @RequestParam String password) {
        // 对密码进行加密
        // 创建用户对象并保存到数据库
        User user = new User();
        user.setUsername(username);
        user.setPassword(SecurityUtils.encodePassword(password));
        // todo 保存到数据库
        // userRepository.save(user);
        log.info("保存到数据库：{}", JSONUtil.toJsonStr(user));
        return Result.success("注册成功", user);
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestParam String username, @RequestParam String password) {
        // todo 模拟数据库查询
        User user = new User();
        user.setId(1L);
        user.setUsername("Tellsea");
        user.setPassword("$2a$10$MyEKUdabJDBkzBqAWUByLe2G6k2UuweepWvPRWwKmm.3nv/fJelk6");
        if (Objects.nonNull(user) && SecurityUtils.matchPassword(password, user.getPassword())) {
            // 用户名密码匹配，创建Authentication对象
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            // 将Authentication对象设置到SecurityContextHolder中
            SecurityUtils.setAuthentication(authentication);
            String token = jwtTokenUtils.generateToken(user.getUsername());
            jwtTokenUtils.cacheToken(token, user.getUsername());
            return Result.success("登录成功", token);
        }
        return Result.success("登录失败，用户名或密码错误");
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/getInfo")
    public Result<User> getInfo() {
        return Result.success("获取成功", SecurityUtils.getCurrentUser());
    }
}
